import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/app/controllers/downloader_controller.dart';
import 'package:flutter_app/app/models/movie.dart';
import 'package:flutter_app/config/keys.dart';
import 'package:flutter_app/resources/widgets/player_widget.dart';
import 'package:flutter_app/resources/widgets/url.dart';
import 'package:nylo_framework/nylo_framework.dart';
import '/app/controllers/play_controller.dart';
import 'package:flutter_app/resources/widgets/detail_widget.dart';
import 'package:flutter_app/resources/widgets/cast_widget.dart';

class PlayPage extends NyStatefulWidget<PlayController> {
  static RouteView path = ("/play", (_) => PlayPage());

  PlayPage({super.key}) : super(child: () => _PlayPageState());
}

class _PlayPageState extends NyPage<PlayPage>
    with SingleTickerProviderStateMixin {
  /// [PlayController] controller
  PlayController get controller => widget.controller;

  late MoviesList movie;
  List<List<Map<String, String>>> sources = [];
  int origin = 0; // Default play source 0
  String url = "";
  String name = "";
  bool isLocalfile = false;
  TabController? _tabController;
  LoadingStyle get loadingStyle => LoadingStyle.normal(
        child: CupertinoActivityIndicator(),
      );
  @override
  get init => () async {
        final data = widget.data();
        if (data is MoviesList) {
          await setHistory(data);
          movie = data;
        } else {
          movie = MoviesList(); // Fallback empty movie
          NyLogger.error("Invalid movie data received in PlayPage");
        }

        sources = movie.vodPlayUrl!.split('\$\$\$').map((source) {
          return source
              .split('#')
              .where((e) => e.contains('\$'))
              .map((episode) {
            var parts = episode.split('\$');
            return {'name': parts[0], 'url': parts[1]};
          }).toList();
        }).toList();

        if (sources.isNotEmpty) {
          sources = sources
              .map((source) => source
                  .where((item) => item["url"]?.contains(".m3u8") ?? false)
                  .toList())
              .where((source) => source.isNotEmpty)
              .toList();
          _tabController = TabController(
            length: sources.length,
            vsync: this,
          );
          setState(() {
            url = sources[origin][0]["url"] ?? "";
            name = sources[origin][0]["name"] ?? "未知";
          });
        }
        NyLogger.dump(movie.localfile?.isEmpty, "localfile is empty");
        // 打印 movie.localfile 类型
        // 如果localfile不为空，则播放本地文件
        if (movie.localfile != null && movie.localfile!.isNotEmpty) {
          setState(() {
            isLocalfile = true;
            url = movie.localfile!;
          });
        }
      };

  void _handleEpisodeClick(String u) {
    if (u == url) return; // Skip if same URL
    var i = sources[origin].indexWhere((item) => item["url"] == u);
    var n = sources[origin][i]["name"] ?? "未知";
    setState(() {
      url = u;
      name = n;
    });
    print("Clicked episode: $u");
  }

  void playFinish(String currentUrl) {
    print("Play finished: $currentUrl");
    var i = sources[origin].indexWhere((item) => item["url"] == currentUrl);
    if (sources[origin].length - 1 > i) {
      // Play next episode
      _handleEpisodeClick(sources[origin][i + 1]["url"]!);
    }
  }

  @override
  void dispose() {
    _tabController?.dispose();
    super.dispose();
  }

  @override
  Widget view(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Center(
          child: Text("${movie.vodName} - $name"),
        ),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.only(bottom: 30),
            child: Column(
              children: [
                // Video Player Section
                Player(
                  key: UniqueKey(),
                  url: url,
                  playFinish: playFinish,
                ),
                if (!isLocalfile)
                  MovieAction(movie: movie, url: url, name: name),
                MovieDetail(),
                // Category Tab Section
                if (!isLocalfile)
                  Padding(
                    padding: EdgeInsets.all(8),
                    child: _buildEpisode(),
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget MovieDetail() {
    return Padding(
      padding: EdgeInsets.all(8.0),
      child: Column(
        spacing: 6,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                "${movie.vodName}(${movie.vodClass})",
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Expanded(child: Container()),
              Container(
                padding: EdgeInsets.only(
                  left: 8,
                  right: 2,
                  top: 2,
                  bottom: 2,
                ),
                child: GestureDetector(
                  onTap: () {
                    showModalBottomSheet(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(4),
                          topRight: Radius.circular(4),
                        ),
                      ),
                      sheetAnimationStyle: AnimationStyle(
                        curve: Curves.bounceIn,
                        duration: Duration(
                          milliseconds: 500,
                        ),
                      ),
                      context: context,
                      builder: (context) => Container(
                        margin: EdgeInsets.only(bottom: 20), // 调整底部间距
                        height: MediaQuery.of(context).size.height / 3,
                        child: Padding(
                          padding: EdgeInsets.only(
                            top: 10,
                            left: 10,
                            right: 10,
                          ),
                          child: SingleChildScrollView(
                            child: Detail(movie: movie),
                          ),
                        ),
                      ),
                    );
                  },
                  child: Row(
                    mainAxisSize: MainAxisSize.min, // 使Row只占用必要的空间
                    children: [
                      Text(
                        "详情",
                        style: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      SizedBox(width: 0), // 添加间距
                      Icon(Icons.chevron_right, size: 16), // 右侧箭头图标
                    ],
                  ),
                ),
                decoration: BoxDecoration(
                  border: Border.all(
                    color: Colors.black,
                    width: 1,
                  ),
                  borderRadius: BorderRadius.circular(8),
                ),
              )
            ],
          ),
          Text(
            "${movie.vodSub ?? ""}/${movie.vodYear ?? ""}(${movie.vodArea ?? ""})/${movie.vodLang}",
            style: TextStyle(
              fontSize: 10,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEpisode() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      spacing: 4,
      children: [
        // 数据源
        Row(
          children: sources.isNotEmpty
              ? sources.asMap().entries.map((entry) {
                  final index = entry.key;
                  // final source = entry.value;
                  return GestureDetector(
                    onTap: () {
                      print("点击了第 $index 集"); // 打印索引
                      setState(() {
                        origin = index;
                      });
                      // 也可以在这里执行其他操作，比如跳转播放
                    },
                    child: Text(
                      "选集",
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ), // 显示索引（可选）
                  );
                }).toList()
              : [const Text("暂无资源")],
        ),
        EpisodeGrid(
          episodes: sources[origin],
          onEpisodeTap: _handleEpisodeClick,
          selectedUrl: url,
        ),
      ],
    );
  }

  Future<void> setHistory(MoviesList movie) async {
    try {
      // Read raw data from storage
      dynamic rawHistory = await storageRead(Keys.history);
      print("history${rawHistory}");
      // Convert raw data to List<MoviesList>
      List<MoviesList> history = [];
      if (rawHistory != null) {
        if (rawHistory is List) {
          history = rawHistory.map<MoviesList>((item) {
            if (item is MoviesList) {
              return item;
            } else if (item is Map<String, dynamic>) {
              return MoviesList.fromJson(item); // Assuming you have fromJson
            }
            throw Exception('Invalid history item type');
          }).toList();
        }
      }

      // Remove if movie with same vodName already exists
      history.removeWhere((e) => e.vodName == movie.vodName);

      // Insert new movie at the beginning
      history.insert(0, movie);

      // Save updated history
      await storageSave(Keys.history, history.map((m) => m.toJson()).toList());
    } catch (e) {
      print("Error in setHistory: $e");
      rethrow;
    }
  }
}

class MovieAction extends StatelessWidget {
  final MoviesList movie;
  final String url;
  final String name;
  DownloaderController get downloaderController => DownloaderController();

  MovieAction({
    super.key,
    required this.movie,
    required this.url,
    required this.name,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        spacing: 4,
        children: [
          GestureDetector(
            onTap: () async {
              final fileName = '${movie.vodName}_${name}.m3u8';
              var response = await downloaderController.downloadVideo(
                  "site", url, fileName, jsonEncode(movie.toJson()));
              // Show success message
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text(response)),
              );
            },
            child: Container(
              padding: EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: Theme.of(context).primaryColor,
                borderRadius: BorderRadius.circular(
                  10,
                ),
              ),
              child: Row(
                children: [
                  Icon(Icons.download, color: Colors.white, size: 14),
                  Text(
                    "下载",
                    style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              showModalBottomSheet(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(4),
                    topRight: Radius.circular(4),
                  ),
                ),
                sheetAnimationStyle: AnimationStyle(
                  curve: Curves.bounceIn,
                  duration: Duration(
                    milliseconds: 500,
                  ),
                ),
                context: context,
                builder: (context) => Container(
                  margin: EdgeInsets.only(bottom: 20, top: 20), // 调整底部间距
                  height: MediaQuery.of(context).size.height / 4,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    spacing: 4,
                    children: [
                      Expanded(
                        child: Cast(
                          title: movie.vodName!,
                          cover: movie.vodPic!,
                          url: url,
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                        },
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 16.0),
                          child: Container(
                            decoration: BoxDecoration(
                              color: Theme.of(context).primaryColor,
                              borderRadius: BorderRadius.circular(
                                10,
                              ),
                            ),
                            padding: const EdgeInsets.all(8.0),
                            child: Center(
                              child: Text(
                                "取消",
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 14,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
            child: Container(
              padding: EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: Theme.of(context).primaryColor,
                borderRadius: BorderRadius.circular(
                  10,
                ),
              ),
              child: Row(
                children: [
                  Icon(Icons.cast, color: Colors.white, size: 14),
                  Text(
                    "投屏",
                    style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Theme.of(context).primaryColor,
              borderRadius: BorderRadius.circular(
                10,
              ),
            ),
            child: Row(
              children: [
                Icon(Icons.favorite, color: Colors.white, size: 14),
                Text(
                  "收藏",
                  style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
